import 'dart:async';

import 'package:aio/aio.dart';
import 'package:aio/src/route/refresh/easyrefresh/easy_classical_footer.dart';
import 'package:aio/src/route/refresh/easyrefresh/easy_classical_header.dart';
import 'package:flutter/material.dart';
import 'package:app/generated/app_strings.dart';
import 'package:app/src/http/bean/wroks/contract_bean.dart';
import 'package:app/src/http/bean/wroks/search_bean.dart';
import 'package:app/src/http/bean/ywx_limit.dart';
import 'package:app/src/http/model/review_model.dart';
import 'package:app/src/manager/ywx_manager.dart';
import 'package:app/src/ui/app_ui.dart';
import 'package:app/src/ui/dialog/dailog.dart';
import 'package:app/src/ui/popuwindow/popuwindow_search.dart';
import 'package:app/src/ui/route/helper/route_helper.dart';
import 'package:app/src/ui/route/works/public/items/ui_card.dart';
import 'package:app/src/utils/image_path_utils.dart';

// import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:easy_refresh/easy_refresh.dart';

import '../../../../../http/bean/worksdo/equipment_management_bean.dart';
import '../../../../../http/bean/worksdo/material_requisition_bean.dart';
import '../../../../../http/model/equipment_management_model.dart';
import '../../../../../http/model/material_requisition_model.dart';
import '../../../../../manager/audit_manager.dart';
import '../../../works/public/review_submitted.dart';
import 'content_list.dart';

///审核列表
class ReviewList2 extends StatefulWidget {
  static bool windowRefresh = false; //判断是否刷新，防止window平台无法自动刷新。
  static setWindowRefresh() {
    if (PlatformUtils.isWindows()) {
      ReviewList2.windowRefresh = true;
    } else {
      ReviewList2.windowRefresh = false;
    }
  }

  ///审核类型
  YwxItem item;

  ///搜索条件
  SearchInfo searchInfo;

  ///是否刷新
  bool isRefresh = true;

  ///是否切换了菜单
  bool isSwitchMenu = false;

  ReviewList2(this.item, this.searchInfo, this.isRefresh, this.isSwitchMenu);

  @override
  _ReviewListState createState() {
    return _ReviewListState();
  }
}

class _ReviewListState extends State<ReviewList2> {
  _ReviewListPresenter presenter = _ReviewListPresenter();
  EasyRefreshController? _controller;

  @override
  void initState() {
    super.initState();
    _controller = EasyRefreshController(
      controlFinishRefresh: true,
      controlFinishLoad: true,
    );
    // print(
    //     '=====================================================================状态初始化');
    ReviewList2.setWindowRefresh();
    windowRefresh();
  }

  ///window平台刷新
  windowRefresh() {
    if (ReviewList2.windowRefresh) {
      ReviewList2.windowRefresh = false;
      if (PlatformUtils.isWindows()) {
        presenter.searchInfo = widget.searchInfo;
        presenter.item = widget.item;
        presenter?.getWorkOvertimeApprovallist(context, 1, () {
          setState(() {
            //resetLoadState 刷新完成。
            // _controller?.resetLoadState();
            IndicatorResult result = IndicatorResult.success; //成功
            _controller?.finishRefresh(result,
                true); //第二个参数最好设置为true，不然会报错：If you want to modify the result, you can set force to true.
            _controller?.resetFooter();
          });
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    AuditManager.getAuditManager()
        .setDetailsWithAuto(false, "review_list.dart"); //fixme 不在审核详情页面。
    presenter._state = this;
    windowRefresh();
    // print(
    //     '=====================================================================视图构建${presenter.datas?.length}');
    presenter.searchInfo = widget.searchInfo;
    presenter.item = widget.item;
    if (widget.isSwitchMenu) {
      presenter?.datas?.clear(); //fixme 旧数据清空；防止数据有残留。
      presenter?.getWorkOvertimeApprovallist(context, 1, () {
        setState(() {
          //resetLoadState 刷新完成。
          // _controller?.resetLoadState();
          IndicatorResult result = IndicatorResult.success; //成功
          _controller?.finishRefresh(result,
              true); //第二个参数最好设置为true，不然会报错：If you want to modify the result, you can set force to true.
          _controller?.resetFooter();
        });
      });
      widget.isSwitchMenu = false;
    }
    // print("页面初始化，是否刷新：${widget.isRefresh} mounted:${mounted}");
    if (widget.isRefresh) {
      AppUi.easyRefreshcallRefresh(_controller);
      widget.isRefresh = false;
    }
    return EasyRefresh(
      controller: _controller,
      // firstRefresh: true,
      refreshOnStart: true,
      header: EasyClassicalHeader(
        context,
        refreshText: AppStrings.of(context).refreshText,
        refreshReadyText: AppStrings.of(context).refreshReadyText,
        refreshingText: AppStrings.of(context).refreshingText,
        refreshedText: AppStrings.of(context).refreshedText,
        refreshFailedText: AppStrings.of(context).refreshFailedText,
      ),
      //footer 尾部，上拉加载更多布局
      footer: EasyClassicalFooter(
        context,
        loadText: AppStrings.of(context).loadText,
        loadReadyText: AppStrings.of(context).loadReadyText,
        loadingText: AppStrings.of(context).loadingText,
        loadedText: AppStrings.of(context).loadedText,
        loadFailedText: AppStrings.of(context).loadFailedText,
        noMoreText: AppStrings.of(context).noMoreText,
        infoText: AppStrings.of(context).infoText +
            '${DateTimeUtils.getDateTimeWithTime()}',
        showInfo: true,
      ),
      onRefresh: () async {
        // print("==================开始刷新 mounted:$mounted");
        if (mounted) {
          Completer<void> completer = new Completer();
          presenter?.getWorkOvertimeApprovallist(context, 1, () {
            completer.complete();
            // print("==================刷新完成 mounted:$mounted");
            if (mounted) {
              setState(() {
                //resetLoadState 刷新完成。
                // _controller?.resetLoadState();
                // var isNoMore = presenter.isNoMore();
                // _controller?.finishRefresh(success: true, noMore: isNoMore);
                IndicatorResult result = IndicatorResult.success; //成功
                _controller?.finishRefresh(result,
                    true); //第二个参数最好设置为true，不然会报错：If you want to modify the result, you can set force to true.
                _controller?.resetFooter();

                ///fixme 扫描自动跳转。
                var b =
                    presenter?.searchInfo?.isScanDeviceCodingResult ?? false;
                if (b &&
                    (presenter?.datas != null &&
                        presenter!.datas!.length == 1)) {
                  var data = presenter.datas![0];
                  goTicketCenterDetailsRoute(context, data);
                }
                presenter?.searchInfo?.isScanDeviceCodingResult =
                    false; //fixme 恢复原样。
              });
            }
          });
          await completer.future;
        }
      },
      onLoad: () async {
        var isNoMore = presenter.isNoMore(); //提前判断是否有更多数据
        if (isNoMore) {
          //没有更多数据了
          if (mounted) {
            setState(() {
              // _controller?.finishLoad(success: true, noMore: isNoMore);
              IndicatorResult result = IndicatorResult.success; //加载成功
              if (isNoMore) {
                result = IndicatorResult.noMore; //没有更多数据了。
              }
              _controller?.finishLoad(result, true);
            });
          }
        } else {
          //还有更多数据
          Completer<void> completer = new Completer();
          presenter?.getWorkOvertimeApprovallist(context, presenter.PageNo + 1,
              () {
            completer.complete();
            if (mounted) {
              setState(() {
                var isNoMore = presenter.isNoMore();
                // _controller?.finishLoad(success: true, noMore: isNoMore);
                IndicatorResult result = IndicatorResult.success; //加载成功
                if (isNoMore) {
                  result = IndicatorResult.noMore; //没有更多数据了。
                }
                _controller?.finishLoad(result, true);
              });
            }
          });
          await completer.future;
        }
      },
      //slivers 主布局
      child: CustomScrollView(slivers: <Widget>[
        SliverList(
          delegate: SliverChildBuilderDelegate(
            (context, index) {
              return _item(context, index);
            },
            childCount: presenter.datas?.length ?? 0,
          ),
        ),
      ]),
    );
  }

  Widget _item(BuildContext context, int index) {
    EquipmentInfo data = presenter.datas![index];
    List<Widget> children = [];

    ///fixme 第一行
    var _str =
        " ${index + 1}.${AppStrings.of(context).TicketNo}:${data.RepairNo}"; //序号.工单号:
    children.add(Row(
      children: [
        Image.asset(
          ImagePathUtils.getPathWithImageEntry("ic_entry.png"),
          width: 14,
        ),
        Text(
          _str, //ReviewTypeName
          style: AppStyle.textStyleWithEntryTitle(),
        )
      ],
    ));
    //中间内容
    children.add(ContentList2.ywxItem(context, presenter.item, data));
    //最后一行
    var lastRow = Row(
      children: [
        Expanded(
          child: Text(''),
        ),
        MaterialButton(
          onPressed: () {
            AppDialog.showDialogWithAlert(context,
                    content: AppStrings.of(context).confirmDelete)
                ?.then((value) {
              if (value != null && value) {
                del(context, data);
              }
            });
          },
          shape: RoundedRectangleBorder(
              side: BorderSide.merge(
                  BorderSide(color: Colors.blueAccent, width: 1),
                  BorderSide.none),
              borderRadius: BorderRadius.all(Radius.circular(20))),
          child: Text(
            AppStrings.of(context).delete, //fixme 删除
            style: AppStyle.textStyleWithEntryTitleBlue(),
          ),
        ),
        AppUi.getSizeBox(width: 24),
        MaterialButton(
          onPressed: () {
            //跳转到非审核类详情页面
            // AppRouteHelper.goWorksDetails3(context, widget.item)?.then((value) {
            //   if (value != null || isRefreshPreviousAppList) {
            //     isRefreshPreviousAppList = false;
            //     AppUi.easyRefreshcallRefresh(_controller); //重新刷新。
            //   }
            // });
            // AppRouteHelper.goTicketCenterDetailsRoute(context, data)
            //     ?.then((value) {
            //   if (value != null || isRefreshPreviousAppList) {
            //     isRefreshPreviousAppList = false;
            //     AppUi.easyRefreshcallRefresh(_controller); //重新刷新。
            //   }
            // });
            goTicketCenterDetailsRoute(context, data);
          },
          shape: RoundedRectangleBorder(
              side: BorderSide.merge(
                  BorderSide(color: Colors.blueAccent, width: 1),
                  BorderSide.none),
              borderRadius: BorderRadius.all(Radius.circular(20))),
          child: Text(
            AppStrings.of(context).Sendorders, //fixme 派单
            style: AppStyle.textStyleWithEntryTitleBlue(),
          ),
        )
      ],
    );
    children.add(Container(
      child: lastRow,
      height: 35,
      padding: EdgeInsets.zero,
      margin: EdgeInsets.zero,
    ));
    var column = Column(
      mainAxisAlignment: MainAxisAlignment.start,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: children,
    );
    return UiCard.build(context, column);
  }

  ///跳转到工单中心详情页面。
  goTicketCenterDetailsRoute(BuildContext context, EquipmentInfo data) {
    AppRouteHelper.goTicketCenterDetailsRoute(context, data)?.then((value) {
      // print("=====================$value\t$isRefreshPreviousAppList");
      if (value != null || isRefreshPreviousAppList) {
        // print("===================列表页面刷新中：$_controller");
        isRefreshPreviousAppList = false;
        // _controller?.callRefresh(force: true); //重新刷新。
        AppUi.easyRefreshcallRefresh(_controller);
      }
    });

    ///在我的工单MyworkorderRoute页面关闭的时候，制空。
    LibRouteHelper.setResult((value) {
      if (value != null || isRefreshPreviousAppList) {
        // print("===================列表页面刷新中：$_controller");
        isRefreshPreviousAppList = false;
        // _controller?.callRefresh(force: true); //重新刷新。
        AppUi.easyRefreshcallRefresh(_controller);
      }
    });
  }

  ///删除工单
  del(BuildContext context, EquipmentInfo data) {
    EquipmentManagementModel.delRepairOrder(context, data, true)?.then((value) {
      isRefreshPreviousAppList = true; //fixme true返回上一个页面，列表会刷新。
      if (value.isSuccessForCode()) {
        Toast.showSuccess(AppStrings.of(context).deleteSuccess, context); //删除成功
        AppUi.easyRefreshcallRefresh(_controller, delayed: false); //重新刷新
      } else {
        //提示错误信息
        AppDialog.showDialogWithInfo(context, content: value.MsgDetail);
        AppUi.easyRefreshcallRefresh(_controller, delayed: false); //失败也重新刷新
      }
    });
  }
}

class _ReviewListPresenter {
  State? _state = null;

  bool mounted() {
    return _state?.mounted ?? false;
  }

  ///审核类型
  YwxItem? item = null;

  ///搜索条件
  SearchInfo? searchInfo = null;

  ///当前页码，从1开始
  int PageNo = 1;

  //总数据个数
  int TotalNum = 0;

  List<EquipmentInfo>? datas;

  ///判断是否没有更多数据了
  bool isNoMore() {
    if (datas != null && datas!.length > 0) {
      if (datas!.length >= TotalNum) {
        return true;
      }
    }
    return false;
  }

  ///获取待审核类型
  getWorkOvertimeApprovallist(
      BuildContext context, int PageNo, ResponseCallbackWithVoid response) {
    // print(
    //     '=====================================================================PageNo:$PageNo\t${isNoMore()}\tReviewType:$item ${item?.ReviewType}');
    if (!(searchInfo?.isOvertimeHours() ?? true)) {
      delayedWithMilliSeconds(500, () {
        response?.call();
        if (mounted()) {
          AppDialog.showDialogWithInfo(context,
              content: AppStrings.of(context)
                  .OvertimeHoursStart2Mes2); //搜索条件,开始时长不能大于结束时长!
        }
      });
      return;
    }
    EquipmentManagementModel.GetRepairOrderList(context, false,
            PageNo: PageNo.toString(), searchInfo: searchInfo)
        ?.then((value) {
      if (value == null) {
        if (mounted()) {
          // AppDialog.showDialogWithInfo(context,
          //     content: AppStrings.of(context).net_error_02); //服务器连接失败
          AppDialog.showDialogWithInfo(context,
              content: AppStrings.of(context).net_error_0); //网络连接失败
        }
      } else {
        if (value.isSuccessForCode()) {
          if (value.isSuccessForData()) {
            TotalNum = value.TotalRowCount;
            if (PageNo <= 1) {
              datas = value.Data;
            } else {
              datas!.addAll(value.Data!);
            }
            this.PageNo = PageNo;
            // print(
            //     '==============================================================个数：${datas?.length}\tTotalNum:${TotalNum}\tPageNo:$PageNo');
          } else {
            if (PageNo <= 1) {
              datas?.clear();
            }
            if (PageNo <= 1 || !isNoMore()) {
              //数据为空
              if (!isShowPopuMenuWithSearch) {
                if (mounted()) {
                  AppDialog.showDialogWithInfo(context,
                      content: AppStrings.of(context).dataEmpty);
                }
              }
            }
          }
        } else {
          if (!isShowPopuMenuWithSearch) {
            if (PageNo <= 1) {
              datas?.clear();
            }
            if (mounted()) {
              AppDialog.showDialogWithInfo(context, content: value?.MsgDetail);
            }
          }
        }
      }
      response?.call();
    });
  }
}
